<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ include file="../session.jsp"%>
<!DOCTYPE html>
<html lang="ko">
  <head>
  	<%@ include file="../head.jsp"%>${alert}
  	<style>
  		#modalId {
  			width: 800px;
  		}
  	</style>
  	<link rel="stylesheet" type="text/css" href="assets/css/lightbox.css" />
  	<!-- Javascript -->
	<script src="assets/js/jquery.js"></script>
	<script src="assets/js/bootstrap.min.js"></script>
	<script src="assets/js/lightbox-2.6.min.js"></script>
	<script>
		arr = new Array();
	</script>
  </head>
  <body>
  	<%@ include file="../menu.jsp"%>
  	
  	<!-- .modal -->
	<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
		<!-- .modal-dialog -->
		<div class="modal-dialog" id="modalId">
			<!-- .modal-content -->
			<div class="modal-content">
				<!-- 제목 -->
				<div class="modal-header">
					<!-- 닫기버튼 -->
					<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
						&times;
					</button>
					<h4 class="modal-title" id="myModalLabel">카테고리 추가하기</h4>
				</div>
				<!-- 내용 -->
				<div class="row">
					<div class="col-md-2"></div>
					<div class="col-md-4">
						<select class="form-control" name="firstCategory">
							<option value="default">- 1차카테고리 -</option>
							<c:forEach items="${first}" var="first">
								<option value="${first.idFirstCategory}">${first.firstCategoryText}</option>
							</c:forEach>
						</select>
					</div>
					<div class="col-md-4">
						<select class="form-control" name="secondCategory">
							<option value="default">- 1차를 먼저 선택하여 주세요 -</option>
						</select>
					</div>
					<div class="col-md-2"></div>
				</div>
				<!-- 하단 -->
				<div class="modal-footer">
					<button type="button" class="btn btn-default" data-dismiss="modal">
						닫기
					</button>
					<button type="button" class="btn btn-primary" id="cateAdd">
						추가
					</button>
				</div>
			</div>
			<!-- /.modal-content -->
		</div>
		<!-- /.modal-dialog -->
	</div>
	<!-- /.modal -->
  	
	<div class="container">
		<div class="page-header">
			<h2>제품 조회/수정</h2>
		</div>

		<form id="updateProduct" class="form-horizontal" role="form" method="post" action="updateProduct.do" enctype="multipart/form-data">
			<fieldset>
			
				<input type="hidden" name="id" value="${cmd.idProduct}"/>
				<input type="hidden" name="page" value="${page}"/>
				<input type="hidden" name="pageCnt" value="${pageCnt}"/>
				<input type="hidden" name="where" value="${where}"/>
				<input type="hidden" name="order" value="${order}"/>
			
				<div class="form-group">
					<label for="isDisplay" class="col-md-2 control-label">상태</label>
					<div class="col-md-10">
						<c:choose>
							<c:when test="${cmd.isDisplay == 1}">
								<label class="radio-inline"><input type="radio" name="isDisplay" value="1" checked> 노출</label>
								<label class="radio-inline"><input type="radio" name="isDisplay" value="0"> 미노출</label>
							</c:when>
							<c:otherwise>
								<label class="radio-inline"><input type="radio" name="isDisplay" value="1"> 노출</label>
								<label class="radio-inline"><input type="radio" name="isDisplay" value="0" checked> 미노출</label>
							</c:otherwise>
						</c:choose>
					</div>
				</div>

				<div class="form-group">
					<label for="idProduct" class="col-md-2 control-label">제품번호</label>
					<div class="col-md-10">
						<p class="form-control-static">${cmd.idProduct}</p>
					</div>
				</div>

				<div class="form-group">
					<label for="productTitle" class="col-md-2 control-label">제품명</label>
					<div class="col-md-10">
						<input type="text" class="form-control" name="productTitle" value="${cmd.productTitle}"/>
					</div>
				</div>

				<div class="form-group">
					<label for="brand" class="col-md-2 control-label">브랜드</label>
					<div class="col-md-10">
						<select name="brand" class="form-control">
							<option>- 선택하세요 -</option>
							<c:forEach items="${brand}" var="brand">
								<option value="${brand.idBrand}" <c:if test="${brand.idBrand == cmd.idBrand}">selected</c:if>>${brand.brandTitle}</option>
							</c:forEach>
						</select>
					</div>
				</div>
				
				<div class="form-group">
					<label for="first" class="col-md-2 control-label">카테고리</label>
					<div class="col-md-10">
						<p class="form-control-static">
							<a data-toggle="modal" href="#myModal" id="cateAddClick">추가하기</a>
						</p>
						<div id="category_add">
							<c:forEach items="${cmd.cateList}" var="list">
								<div class="row cate_item">
									<div class="col-md-5">
										<select class="form-control" name="first">
											<option value="${list.idFirstCategory}">${list.idFirstCategoryValue}</option>
										</select>
									</div>
									<div class="col-md-5">
										<select class="form-control" name="second">
											<option value="${list.idSecondCategory}">${list.idSecondCategoryValue}</option>
										</select>
									</div>
									<div class="col-md-2">
										<input type="button" class="btn btn-block" id="del${list.idSecondCategory}" value="삭제" />
									</div>
									<script>
										$(function() {
											arr.push("${list.idSecondCategory}");
											
											$("#del${list.idSecondCategory}").click(function() {
												if (confirm("정말 삭제하시겠습니까?")) {
													$(this).parents(".cate_item").remove();
													arr = jQuery.grep(arr, function(value) {
														return value != "${list.idSecondCategory}";
													});
													$.ajax({
														async: false,
														url: "ajax/keyword.jsp",
														data: "second=${list.idSecondCategory}",
														dataType: "xml",
														timeout: 30000,
														cache: false,
														async: false,
														success: function(req) {
															var delete_arr = new Array();
															$(req).find("item").each(function() {
																var name = $(this).find("name").text();
																var value = $(".keyWord");
																for (var i=0; i<value.length; i++) {
																	if (name == value[i].value) {
																		$("input[name=keyWord]").filter('input[value='+name+']').parent(".checkbox-inline").remove();
																		delete_arr.push(name);
																	}
																}
															});
															alert("등록되었던 키워드중 삭제하신 카테고리에 해당하는\n<" + delete_arr + ">\n키워드가 삭제되었습니다.");
															
														},
														error: function(xhr, status, error) {
															alert("status: " + status + " / error-code: " + xhr.status + " " + error);
														}
													});
												}
											});
											$.ajax({
												async: false,
												url: "ajax/keyword.jsp",
												data: "second=${list.idSecondCategory}",
												dataType: "xml",
												timeout: 30000,
												cache: false,
												async: false,
												success: function(req) {
													$(req).find("item").each(function() {
														var name = $(this).find("name").text();
														var item = "<label class='checkbox-inline'><input type='checkbox' name='keyWord' value='" + name + "'>" + name + "</label>";
														$("#keyWord${list.idSecondCategory}").append(item);
													});
												},
												error: function(xhr, status, error) {
													alert("status: " + status + " / error-code: " + xhr.status + " " + error);
												}
											});
										});
									</script>
									<div>
										<label for="keyWord" class="col-md-1 control-label">키워드</label>
										<div class="col-md-11" id="keyWord${list.idSecondCategory}"></div>
									</div>
									<div>&nbsp;</div>
								</div>
							</c:forEach>
						</div>
					</div>
				</div>
				
				<div class="form-group">
					<label for="keyWord" class="col-md-2 control-label">키워드</label>
					<div class="col-md-10">
						<c:if test="${keyWord == null }"><p class="form-control-static">등록된 키워드가 없습니다.</p></c:if>
						<c:forEach items="${keyWord}" var="keyWord">
							<label class="checkbox-inline">
								<input type="checkbox" name="keyWord" class="keyWord" value="${keyWord}" checked/>${keyWord}
							</label>
						</c:forEach>
					</div>
				</div>

				<div class="form-group">
					<label for="productImg" class="col-md-2 control-label">사진</label>
					<div class="col-md-10">
						<div class="row">
							<div class="col-md-4">
								<p class="form-control-static">
									<a href="download.jsp?${cmd.image}" data-lightbox="roadtrip" title="${cmd.productTitle}">
										<img src="download.jsp?${cmd.image}" class="img-thumbnail img-responsive"/>
									</a>
								</p>
							</div>
							<div class="col-md-8">
								<br/>
								<ul>
									<li>항번: ${cmd.image.idAttacheFile}</li>
									<li>원본 파일 이름: ${cmd.image.fileOrgName}</li>
									<li>파일 크기: ${cmd.image.fileSize}byte</li>
									<li>업로드된 파일 이름: ${cmd.image.fileSaveName}</li>
									<li>업로드된 폴더 경로: ${cmd.image.fileDir}</li>
									<li>파일 타입: ${cmd.image.fileType}</li>
								</ul>
								&nbsp;&nbsp;&nbsp;&nbsp;
								<button type="button" class="btn btn-sm" id="imgEdit">변경</button>
								<br/><br/>
								<div id="imgDiv"><input type="file" class="form-control" name="editImg"/></div>
							</div>
						</div>
					</div>
				</div>

				<div class="form-group">
					<label for="volume" class="col-md-2 control-label">용량</label>
					<div class="col-md-10">
						<input type="text" class="form-control" name="volume" value="${cmd.volume}"/>
					</div>
				</div>

				<div class="form-group">
					<label for="price" class="col-md-2 control-label">가격</label>
					<div class="col-md-10">
						<input type="number" class="form-control" name="price" value="${cmd.price}"/>
					</div>
				</div>
				
				<div class="form-group">
					<label for="colorType" class="col-md-2 control-label">컬러/타입</label>
					<div class="col-md-10">
						<textarea name="colorType" class="form-control" rows="7">${cmd.colorType}</textarea>
					</div>
				</div>
				
				<div class="form-group">
					<label for="productText" class="col-md-2 control-label">제품설명</label>
					<div class="col-md-10">
						<textarea name="productText" class="form-control" rows="10">${cmd.productText}</textarea>
					</div>
				</div>
				
				<div class="form-group">
					<label for="etc" class="col-md-2 control-label">기타정보</label>
					<div class="col-md-10">
						<div class="table-responsive">
							<table class="table table-condensed">
								<thead>
									<tr class="warning row">
										<th class="text-center col-md-3">평점</th>
										<th class="text-center col-md-3">조회수</th>
										<th class="text-center col-md-3">위시리스트</th>
										<th class="text-center col-md-3">인기도</th>
									</tr>
								</thead>
								<tbody>
									<tr class="text-center row">
										<td class="col-md-3">
											<a href="reviewComment.do?where= AND c.idProduct=${cmd.idProduct}"
												target="_blank">${cmd.ratingAvg} (${cmd.rationCount}건)</a>
										</td>
										<td class="col-md-3">${cmd.readCount}</td>
										<td class="col-md-3">
											<a href="listRegister.do?where= AND idRegister in (SELECT idRegister FROM wishlistmapping WHERE idProduct=${cmd.idProduct})"
												target="_blank">${cmd.wishCount}</a>
										</td>
										<td class="col-md-3">${cmd.productScore}</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>
				</div>

				<div class="form-group">
					<div class="col-md-offset-2 col-md-10">
						<div class="row">
							<div class="col-md-6">
								<button type="submit" class="btn btn-primary btn-block">수정하기</button>
							</div>
							<div class="col-md-6">
								<button type="reset" class="btn btn-warning btn-block">다시작성</button>
							</div>
						</div>
					</div>
				</div>

			</fieldset>
		</form>
	</div>
	<!-- 플러그인 참조 -->
	<script src="assets/js/ckeditor/ckeditor.js"></script>
	<script>
	   var editor;
	   CKEDITOR.on( 'instanceReady', function( ev ) {
	       editor = ev.editor;
	       document.getElementById( 'readOnlyOn' ).style.display = '';
	       editor.on( 'readOnly', function() {
	           document.getElementById( 'readOnlyOn' ).style.display = this.readOnly ? 'none' : '';
	           document.getElementById( 'readOnlyOff' ).style.display = this.readOnly ? '' : 'none';
	       });
	   });
	  
	   function toggleReadOnly( isReadOnly ) {
	       editor.setReadOnly( isReadOnly );
	   }
	</script>
	<!-- 형식검사 클래스 참조 -->
	<script src="assets/js/string.js"></script>
	<script type="text/javascript">
		$(function() {
			
			$("select[name='firstCategory']").change(function() {
				$("select[name='secondCategory']").empty();
				
				var first = $(this).find("option:selected").val();
				
				$("select[name='thirdCategory'] option").remove();
				$("select[name='thirdCategory']").append("<option value='default'>- 2차를 먼저 선택하여 주세요 -</option>");
				
				$.ajax({
					url: "ajax/first.jsp",
					data: "first=" + first,
					dataType: "xml",
					timeout: 30000,
					cache: false,
					async: false,
					success: function(req) {
						$(req).find("item").each(function() {
							var idSecondCategory = $(this).find("idSecondCategory").text();
							var secondCategoryText = $(this).find("secondCategoryText").text();
							
							var option = $("<option>").html(secondCategoryText);
							option.attr({'value' : idSecondCategory});
							
							$("select[name='secondCategory']").append(option);
						});
					},
					error: function(xhr, status, error) {
						alert("status: " + status + " / error-code: " + xhr.status + " " + error);
					}
				});
			});
			
			$("#cateAdd").click(function() {
				
				var firstVal = $("select[name='firstCategory']").val();
				var firstText = $("select[name='firstCategory'] option:selected").text();
				var secondVal = $("select[name='secondCategory']").val();
				var secondText = $("select[name='secondCategory'] option:selected").text();
				if (firstVal == 'default') {
					alert('1차카테고리를 선택하세요.');
					return false;
				}
				if (secondVal == 'default') {
					alert('2차카테고리를 선택하세요.');
					return false;
				}
				
				for (var i=0; i<arr.length; i++) {
					if (arr[i] == secondVal) {
						alert("동일한 2차카테고리는 선택하실수 없습니다.");
						return false;
					}
				}
				
				var result = "<div class='row cate_item'><div class='col-md-5'><select class='form-control' name='first'>"
					+ "<option value='" + firstVal + "'>" + firstText + "</option></select></div><div class='col-md-5'>"
					+ "<select class='form-control' name='second'><option value='" + secondVal + "'>" + secondText + "</option>"
					+ "</select></div><div class='col-md-2'><input type='button' class='btn btn-block' id='del"
					+ secondVal + "' value='삭제'/></div><script>$(function(){$('#del" + secondVal + "').click(function(){if(confirm"
					+ "('정말 삭제하시겠습니까?')){$(this).parents('.cate_item').remove();arr=jQuery.grep(arr,function(value)"
					+ "{return value != " + secondVal + ";});}});});</sc" + "ript><div><label for='keyWord' class='col-md-1 control-label'>키워드</label><div class='col-md-11' id='keyWord" + secondVal + "'></div></div><div>&nbsp;</div></div>";
					
				$("#category_add").append(result);
				
				$.ajax({
					url: "ajax/keyword.jsp",
					data: "second=" + secondVal,
					dataType: "xml",
					timeout: 30000,
					cache: false,
					async: false,
					success: function(req) {
						$(req).find("item").each(function() {
							var name = $(this).find("name").text();
							var item = "<label class='checkbox-inline'><input type='checkbox' name='keyWord' value='" + name + "'>" + name + "</label>";
							$("#keyWord" + secondVal).append(item);
						});
					},
					error: function(xhr, status, error) {
						alert("status: " + status + " / error-code: " + xhr.status + " " + error);
					}
				});
				
				arr.push(secondVal);
				
			});
			
			$("#cateAddClick").click(function() {
				$("select[name='firstCategory'] option:eq(0)").attr("selected", "selected");
				$("select[name='secondCategory'] option").remove();
				$("select[name='secondCategory']").append("<option value='default'>- 1차를 먼저 선택하여 주세요 -</option>");
			});
		});
	</script>
	<script type="text/javascript">
		// jquery main()
		$(function() {
			
			$("#updateProduct").submit(function() {
				
				if (!$("input[name='isDisplay']").is(":checked")) {
					alert("노출상태를 선택해 주세요");
					$("input[name='isDisplay']").focus();
					return false;
				}
				
				if (!$("input[name='productTitle']").val().isValue()) {
					alert("제품명을 입력하세요.");
					$("input[name='productTitle']").focus();
					return false;
				}
				
				if ($("select[name='brand'] > option:selected").index() < 1) {
					alert("브랜드를 선택하세요.");
					$("select[name='brand']").focus();
					return false;
				}
				
				if ($("select[name='first'] > option:selected").index() != 0) {
					alert("카테고리를 선택하세요.");
					return false;
				}
				
				if ($("select[name='second'] > option:selected").index() != 0) {
					alert("2차 카테고리를 선택하세요.");
					return false;
				}
				
				if (!$("input[name='volume']").val().isValue()) {
					alert("용량을 입력하세요.");
					$("input[name='volume']").focus();
					return false;
				}
				
				if (!$("input[name='price']").val().isValue()) {
					alert("가격을 입력하세요.");
					$("input[name='price']").focus();
					return false;
				}
				
				if (!$("input[name='price']").val().isNumber()) {
					alert("가격은 숫자로만 입력이 가능합니다.");
					$("input[name='price']").focus();
					return false;
				}
				
				if (!$("input[name='keyWord']").val().isValue()) {
					alert("키워드를 입력하세요.");
					$("input[name='keyWord']").focus();
					return false;
				}
				
				if (!$("textarea[name='productText']").val().isValue()) {
					alert("제품설명을 입력하세요.");
					$("textarea[name='productText']").focus();
					return false;
				}
				
				if (!confirm("정말 수정하시겠습니까?")) {
					return false;
				}
				
			});
		});
	</script>
	<script>
		$(function() {
			$("#imgDiv").hide();
			
			$("#imgEdit").click(function() {
				$("input[name='editImg']").replaceWith($("input[name='editImg']").clone(true));
				$("#imgDiv").toggle();
			});
		});
	</script>
  </body>
</html>